﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DBCreated : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string dbId ="0";
            string userMsg = "";
            int tmpdbId=0;
            ProxyWrapper.UserProxy.UserDetails _objUser = ((ProxyWrapper.UserProxy.UserDetails)Session["UserObject"]);
            ProxyWrapper.DatabaseServiceWrapper _dbService = new ProxyWrapper.DatabaseServiceWrapper();
            string dbName = Request["databasename"].ToString();
            // string csvFile = Request["username"].ToString();
            HttpPostedFile csvFile = Request.Files["csvfile"];
            byte[] fileData = null;
            using (var binaryReader = new BinaryReader(csvFile.InputStream))
            {
                fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
            }
            bool isCaseSensitive = false;
            if (Request["caseSensitivity"] != null && Request["caseSensitivity"] == "on")
                isCaseSensitive = true;
            
            string[] msg = _dbService.AddDatabase(dbName, isCaseSensitive, _objUser.ClientId, fileData, null);
            if (msg.Length == 2 && Int32.TryParse(msg[0].ToString(), out tmpdbId) && tmpdbId > 0)
            {
                dbId = msg[0].ToString();
                userMsg = msg[1].ToString();
            }
            else if (msg.Length == 2 && Int32.TryParse(msg[0].ToString(), out tmpdbId) && tmpdbId ==0)
            {
                userMsg = "A database already exists with that name."; 
            }
            else if (msg.Length==1 && Int32.TryParse(msg[0].ToString(), out tmpdbId) && tmpdbId > 0)
            {
                userMsg = "Database has been created.";
            }
            else if (msg.Length == 1)
            {
                userMsg = msg[0].ToString();
            }
            else
            {
                userMsg = "Unable to create database.A database already exists with that name.";
            }

            if (tmpdbId>0)
            {
                Response.Redirect("DatabaseSearch.aspx?dbid=" + dbId + "&msg=Database created.&dbName=" + dbName,false);
               
            }
            else
            {
                Response.Redirect("Databases.aspx?msg=" + userMsg);
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error while creating Database " + ex.Message);
        }
    }
}